import bidTabsTpl from './bidTabs.html';
export default function (app) {

  app.directive('bidTabs', bidTabs);

  function bidTabs() {
    'ngInject';
    return {
      restrict: 'E',
      templateUrl: bidTabsTpl,
      controller: bidTabsCtrl,
      compile: compileFn,
      scope: {
        beforeQueryFn: '=',
        queryFn: '=',
        queryBean: '=',
        queryParam: '@',
        queryType: '@',
        teamsData: '=',
        ngDisabled: '@',
      }
    };
  }

  function linkFn(scope, elements, attrs, ctrl) {
    if (attrs.ngDisabled == 'true') {
      elements.parent().removeClass('tabs-main');
    }
  }

  function bidTabsCtrl($q, $rootScope, $scope, $http, paFetchService) {

    function initTabsData() {
      let deferred = $q.defer();
      if ($scope.ngDisabled == 'true') {
        return false;
      }
      if ($rootScope.authorizationInfo && !$rootScope.authorizationInfo.bidsInfo) {
        paFetchService
          .getSectionList()
          .then((resp) => {
            setRootBidsData($rootScope, resp.data);
            query();
            deferred.resolve();
          });
      } else {
        query();
        deferred.resolve();
      }
      return deferred.promise;
    }

    initTabsData().then(function() {
      $scope.$watch('teamsData', function(newVal) {
        if (newVal) {
          computeTeamList();
        }
      });
    })

    function query() {
      if ($scope.queryType == 'bid') {
        $scope.queryBean[$scope.queryParam] = $rootScope.activeBid.bidId;
      } else {
        $scope.queryBean[$scope.queryParam] = $rootScope.activeBid.orgId;
      }

      if ($scope.beforeQueryFn) {
        $scope
          .beforeQueryFn()
          .then($scope.queryFn)
      } else {
        $scope.queryFn();
      }
    }

    function computeTeamList() {
      if (!$scope.teamsData) return;
      if (!$scope.teamsData._origin) {
        $scope.teamsData._origin = angular.copy($scope.teamsData);
      }

      $scope.teamsData.length = 0;
      $scope.teamsData._origin.forEach(function(team, index) {
        if (team.orgUnitId == $rootScope.activeBid.orgId) {
          $scope.teamsData.push(team);
        }
      });
    }

    function setRootBidsData(scope, bidsData) {
      if (bidsData.length) {
        scope.authorizationInfo.bidsInfo = bidsData;
        scope.authorizationInfo.bidsInfo[0].active = true;
        scope.activeBid = scope.authorizationInfo.bidsInfo[0];
      }
    }

    $scope.selectBid = function(bid, $index) {
      $rootScope.authorizationInfo.bidsInfo.forEach(function(item, index) {
        item.active = false;
        if (index == $index) {
          item.active = true;
          $rootScope.activeBid = item;
        }
      });
      query();
      computeTeamList();
    }

  }


  function compileFn(tElement, tAttrs, transclude) {
    tElement.parent().addClass('tabs-main');
    return linkFn;
  }

}